#include<iostream>
#include<cstdlib>
#include<string>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>


int main()
{
    // 重定向问题： cout 往1文件描述符打印 ，cerr 往2号文件描述符打印
    // ./mypipe > log.txt 只会把cout打印在log.txt，cerr打印的错误信息还是会打印在显示屏中
    // 如果想把cerr打印到log.txt中，应该 ./mypipe 2> log.txt
    // 如果想把标准输出和标准错误全部重定向到log.txt中，./mypipe >log.txt 2>&1
    // std::cout << "ok" << std::endl;
    // std::cerr << "no" << std::endl;


    //目标：父进程读取，子进程写入

    // 1.创建管道
    int fds[2] = {0};
    int n = pipe(fds);
    // if(n == 0)
    // {
    //     std::cout << "fds[0]: " << fds[0] << std::endl; //3 读端
    //     std::cout << "fds[1]: " << fds[1] << std::endl; //4 写端
    // }
    if(n != 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }

    // 2.创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        std::cerr << "fork error" << std::endl;
        return 2;
    }
    else if(id == 0)
    {
        // 子进程

        // 3.关闭不需要的fd，关闭read
        ::close(fds[0]);

        int cnt = 0;
        int total = 0;
        while(1)
        {
            std::string message = "h";
            // message += std::to_string(getpid());
            // message += ",";
            // message += std::to_string(cnt);

            //fds[1]
            total += ::write(fds[1],message.c_str(),message.size());
            cnt++;
            std::cout << "total: " << total << std::endl;
            //sleep(1);
        }
        exit(0);
    }
    else
    {
        // 3.关闭不需要的fd,关闭write
        ::close(fds[1]);

        char buffer[1024];
        while(1)
        {
            ssize_t n = ::read(fds[0],buffer,1024);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "child->father,message: " << buffer << std::endl;
            }
        }

        // 父进程
        // pid_t rid = waitpid(id,nullptr,0);
        // std::cout << "father wait child sucess" << rid << std::endl;

        int status = 0;
        pid_t rid = waitpid(id,&status,0);
        std::cout << "father wait child sucess:" << rid << "exit code: " << 
            ((status<<8)&0xFF) << ",exit sig:" << (status & 0x7F) << std::endl;
        
    }


    return 0;
}